use log::error;
use schemars::schema::RootSchema;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::sync::Arc;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AccountToken {
    // api key
    pub binance_key: String,
    // api secret
    pub binance_secret: String,
    // 基础请求地址
    pub basic_url: String,
    // 合约URL地址
    pub future_basic_url: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct BinanceConfig {
    pub accounts_token: AccountToken,
}

// 从配置文件里面读取api配置信息,返回Arc<longport::Config>类型对象
pub fn get_load_global_config() -> AccountToken {
    // 加载配置文件，并映射为对应的对象
    let long_port_config: BinanceConfig = load_config("./config/config-dev.yaml").expect("加载配置失败");
    long_port_config.accounts_token
}
// 加载位置文件
fn load_config<T>(path: &str) -> Option<T>
where
    T: DeserializeOwned,
{
    match serde_yaml::from_str::<RootSchema>(
        &std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Fail to read file:{}", path)),
    ) {
        Ok(root_schema) => {
            let data = serde_json::to_string_pretty(&root_schema).expect("Fail to parse RootSchema!");
            let config = serde_json::from_str::<T>(&data)
                .unwrap_or_else(|_| panic!("Fail to parse config: {}", &data));
            Some(config)
        }
        Err(err) => {
            error!("{}", err);
            None
        }
    }
}